<template>
  <Collapse expandIconPosition="right" class="!mb-24px" :default-active-key="['1']">
    <CollapsePanel :header="alarm.alarmType" key="1">
      <template #extra>
        <Button @click="del" shape="circle" type="text" v-show="!isDisable">
          <Icon :icon="ICON.DELETE" class="!text-24px" />
        </Button>
      </template>
      <div class="alarm-rules">
        <a-input
          v-model:value="alarm.alarmType"
          placeholder="告警类型"
          required
          :disabled="isDisable"
          class="item"
        />
        <!-- 高级设置 -->
        <Collapse expandIconPosition="right" class="!mb-24px">
          <CollapsePanel key="1" header="高级设置">
            <div class="checkBox">
              <Checkbox v-model:checked="alarm.propagate" :disabled="isDisable" class="!mb-24px"
                >传递警报</Checkbox
              >
              <span v-show="alarm.propagate">要传递的关联类型</span>
              <Select
                v-show="alarm.propagate"
                v-model:value="alarm.propagateRelationTypes"
                mode="tags"
                placeholder="要传递的关联类型"
                :open="false"
                :disabled="isDisable"
                class="!mb-24px"
              />
              <Checkbox
                v-model:checked="alarm.propagateToOwner"
                :disabled="isDisable"
                class="!mb-24px"
                >将告警传播给实体所有者（客户或租户）</Checkbox
              >
              <Checkbox
                v-model:checked="alarm.propagateToTenant"
                :disabled="isDisable"
                class="!mb-24px"
                >将告警传播给租户</Checkbox
              >
            </div>
          </CollapsePanel>
        </Collapse>
        <!-- 创建告警规则 -->
        <span class="item">创建告警规则</span>
        <div class="text-24px text-center text-red-500" v-show="alarm.createRule.length === 0"
          >请添加创建告警规则</div
        >
        <div
          class="add-alarm-box"
          v-for="(item, index) in alarm.createRule"
          :key="item.id"
          v-show="alarm.createRule.length != 0"
        >
          <div class="add-alarm-card">
            <div class="left">
              <span>严重程度：</span>
              <Select
                class="!w-full !mt-12px"
                v-model:value="item.Severity"
                :disabled="isDisable"
                placeholder="请选择严重程度"
              >
                <SelectOption
                  v-for="severity in severitys"
                  :key="severity.value"
                  :disabled="isSelectedByOthers(severity.value, item.Severity)"
                >
                  {{ severity.label }}
                </SelectOption>
              </Select>
            </div>
            <Divider type="vertical" class="!h-auto !border-l-2px" />
            <div class="right">
              <div v-show="!item.condition || !item.condition.condition.length" class="item">
                <span class="text-red-500">请添加告警规则条件:</span>
                <Button size="large" shape="circle" type="text" @click="toCondition(index, true)">
                  <Icon :icon="ICON.PLUS" class="!text-24px" />
                </Button>
              </div>
              <div v-if="item.condition && item.condition.condition.length" class="condition">
                <div class="ellipsis">
                  <span class="whitespace-no-wrap mr-12px">条件:</span>
                  <template
                    v-for="(conditionGroup, groupIndex) in item.condition.condition"
                    :key="groupIndex"
                  >
                    <ShowCondition
                      :formData="conditionGroup"
                      :isFirst="groupIndex === 0 ? true : false"
                  /></template>
                </div>

                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditCondition(index, item, true)"
                  v-show="!isDisable"
                >
                  <Icon :icon="ICON.EDIT" class="!text-24px" />
                </Button>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditCondition(index, item, true)"
                  v-show="isDisable"
                >
                  <Icon :icon="ICON.CHECK" class="!text-24px" />
                </Button>
              </div>
              <div v-if="!item.schedule" class="item">
                <span class="text-red-500">请添加启用规则:</span>
                <Button size="large" shape="circle" type="text" @click="toSchedule(index, true)">
                  <Icon :icon="ICON.PLUS" class="!text-24px" />
                </Button>
              </div>
              <div v-if="item.schedule" class="item">
                <span class="mr-12px">启用规则:</span
                ><span>{{ keyWordsTranslation[item.schedule.type] }}</span>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditSchedule(index, item, true)"
                  v-show="!isDisable"
                >
                  <Icon :icon="ICON.EDIT" class="!text-24px" />
                </Button>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditSchedule(index, item, true)"
                  v-show="isDisable"
                >
                  <Icon :icon="ICON.CHECK" class="!text-24px" />
                </Button>
              </div>
              <div class="item">
                <span class="whitespace-nowrap">附加信息:</span>
                <a-textarea
                  v-model:value="item.alarmDetails"
                  :disabled="isDisable"
                  class="!w-full !ml-12px"
                />
              </div>
              <div class="item">
                <span class="whitespace-nowrap">移动端仪表盘:</span>
                <Select
                  class="!w-full !ml-12px"
                  placeholder="未选择移动仪表盘"
                  :options="dashboards"
                  v-model:value="item.dashboardId"
                  :disabled="isDisable"
                  :listHeight="160"
                />
              </div>
            </div>
          </div>
          <div>
            <Button
              size="large"
              shape="circle"
              type="text"
              @click="deleteCreateCondition(index, item.Severity)"
              v-show="!isDisable"
            >
              <Icon :icon="ICON.MINUS_ROUND" class="!text-30px" />
            </Button>
          </div>
        </div>
        <Button @click="addCreateCondition" v-show="!isDisable" class="my-24px"
          ><Icon :icon="ICON.PLUS" class="!text-24px" />添加创建条件</Button
        >
        <!-- 清除告警规则 -->
        <span class="item">创建清除规则</span>
        <div class="text-24px text-center" v-show="alarm.clearRules.length === 0"
          >未配置明确条件</div
        >
        <div
          class="add-alarm-box"
          v-for="(item, index) in alarm.clearRules"
          :key="index"
          v-show="alarm.clearRules.length != 0"
        >
          <div class="add-alarm-card">
            <div class="right">
              <div v-show="!item.condition || !item.condition.condition.length" class="item">
                <span class="text-red-500">请添加告警规则条件</span>
                <Button size="large" shape="circle" type="text" @click="toCondition(index, false)">
                  <Icon :icon="ICON.PLUS" class="!text-24px" />
                </Button>
              </div>
              <div v-if="item.condition && item.condition.condition.length" class="condition">
                <div class="ellipsis">
                  <span class="whitespace-no-wrap mr-12px">条件:</span>
                  <template
                    v-for="(conditionGroup, groupIndex) in item.condition.condition"
                    :key="groupIndex"
                  >
                    <ShowCondition
                      :formData="conditionGroup"
                      :isFirst="groupIndex === 0 ? true : false"
                    />
                  </template>
                </div>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditCondition(index, item, false)"
                  v-show="!isDisable"
                >
                  <Icon :icon="ICON.EDIT" class="!text-24px" />
                </Button>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditCondition(index, item, false)"
                  v-show="isDisable"
                >
                  <Icon :icon="ICON.CHECK" class="!text-24px" />
                </Button>
              </div>
              <div v-if="!item.schedule" class="item">
                <span class="text-red-500">请添加启用规则:</span>
                <Button size="large" shape="circle" type="text" @click="toSchedule(index, false)">
                  <Icon icon="material-symbols-light:add" class="!text-24px" />
                </Button>
              </div>
              <div v-if="item.schedule" class="item">
                <span class="mr-12px">启用规则:</span
                ><span>{{ keyWordsTranslation[item.schedule.type] }}</span>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditSchedule(index, item, false)"
                  v-show="!isDisable"
                >
                  <Icon :icon="ICON.EDIT" class="!text-24px" />
                </Button>
                <Button
                  size="large"
                  shape="circle"
                  type="text"
                  @click="toEditSchedule(index, item, false)"
                  v-show="isDisable"
                >
                  <Icon :icon="ICON.CHECK" class="!text-24px" />
                </Button>
              </div>
              <div class="item">
                <span class="whitespace-nowrap">附加信息:</span>
                <a-textarea
                  v-model:value="item.alarmDetails"
                  :disabled="isDisable"
                  class="!w-full !ml-12px"
                />
              </div>
              <div class="item">
                <span class="whitespace-nowrap">移动端仪表盘:</span>
                <Select
                  class="!w-full !ml-12px"
                  placeholder="未选择移动仪表盘"
                  :options="dashboards"
                  v-model:value="item.dashboardId"
                  :disabled="isDisable"
                  :listHeight="160"
                />
              </div>
            </div>
          </div>

          <Button
            size="large"
            shape="circle"
            type="text"
            @click="deleteClearCondition"
            v-show="!isDisable"
          >
            <Icon icon="ic:baseline-remove-circle-outline" class="!text-30px" />
          </Button>
        </div>

        <Button
          @click="addClearCondition"
          v-show="alarm.clearRules?.length === 0 && !isDisable"
          class="my-24px"
          ><Icon :icon="ICON.PLUS" class="!text-24px" />添加清除条件</Button
        >
      </div>
    </CollapsePanel>
  </Collapse>

  <AlertSchedule @register="registerAlertSchedule" @get-data="getSchedule" :disable="isDisable" />
  <AlertCondition
    @register="registerAlertCondition"
    @get-data="getCondition"
    :disable="isDisable"
  />
</template>

<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import AlertSchedule from './AlertScheduleModel.vue';
  import AlertCondition from './AlarmConditionModel.vue';
  import ShowCondition from './ShowCondition.vue';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import {
    Collapse,
    CollapsePanel,
    Checkbox,
    Select,
    SelectOption,
    Divider,
    Button,
  } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import _ from 'lodash';
  import { nanoid } from 'nanoid';
  import { getDashboards } from '/@/api/thingsborad/profile/assetProfile/assetProfile';
  import { keyWordsTranslation } from '../form.data';
  const emit = defineEmits(['delete', 'update']);
  const props = defineProps({
    data: {
      type: Object,
      required: true,
    },
    disable: { type: Boolean },
  });
  let isDisable = ref<boolean>(false);
  let severitys: Array<any> = [
    { value: 'CRITICAL', label: '危险' },
    { value: 'MAJOR', label: '重要' },
    { value: 'MINOR', label: '次要' },
    { value: 'WARNING', label: '警告' },
    { value: 'INDETERMINATE', label: '不确定' },
  ];
  //记录告警中，告警规则，严重程度select中已经被选中的值
  let selectedSeverity = ref<any>([]);
  let alarm = ref(props.data);
  let dashboards = ref<Array<any>>([]);
  let param = {
    pageSize: 10,
    page: 0,
    sortProperty: 'title',
    sortOrder: 'ASC',
  };
  onMounted(async () => {
    dashboards.value = [];
    //获取移动仪表盘的数据
    try {
      let res = await getDashboards(param);
      dashboards.value = res.data.map((item) => ({
        label: item.name,
        value: JSON.stringify(item.id),
      }));
    } catch (error) {
      console.error('获取移动仪表盘出错', error);
    }
  });
  //记录是创建条件被修改还是清除条件被修改
  let isCreateRule = ref<boolean>(false);
  //记录创建条件数组或清除条件数组谁被添加或修改的下标
  let whoEdit = ref();
  let conditionRule = ref<Recordable>({
    id: '',
    Severity: '',
    condition: '',
    schedule: {
      type: 'ANY_TIME',
      dynamicValue: null,
    },
    alarmDetails: null,
    dashboardId: null,
  });
  function del() {
    emit('delete', alarm.value);
  }
  //添加创建条件
  function addCreateCondition() {
    conditionRule.value.id = '';
    conditionRule.value.id = nanoid();
    const firstMissingObject = severitys.find(
      (obj) => !selectedSeverity.value.some((selected) => obj.value === selected),
    );
    conditionRule.value.Severity = firstMissingObject?.value;
    alarm.value.createRule.push(_.cloneDeep(conditionRule.value));
    conditionRule.value.Severity = '';
  }
  //删除创建条件
  function deleteCreateCondition(i: number, value: string) {
    selectedSeverity.value = selectedSeverity.value.filter((spec: string) => spec !== value);
    alarm.value.createRule.splice(i, 1);
  }

  //添加清除条件
  function addClearCondition() {
    conditionRule.value.id = '';
    conditionRule.value.id = nanoid();
    alarm.value.clearRules.push(_.cloneDeep(conditionRule.value));
  }

  //删除清除条件
  function deleteClearCondition() {
    alarm.value.clearRules = [];
  }
  // 判断severitys中的值是否被已有的创建告警规则中选中
  function isSelectedByOthers(optionValue: string, currentSpec: string) {
    return selectedSeverity.value.includes(optionValue) && optionValue !== currentSpec;
  }
  const [registerAlertSchedule, { openModal: openAlertSchedule }] = useModal();
  const [registerAlertCondition, { openModal: openAlertCondition }] = useModal();
  watch(
    () => alarm.value,
    (nVal) => {
      selectedSeverity.value = [];
      nVal.createRule.map((item) => {
        selectedSeverity.value.push(item.Severity);
      });
      emit('update', alarm.value);
    },
    { deep: true },
  );
  watch(
    () => props.disable,
    (nVal) => {
      isDisable.value = nVal;
    },
    { immediate: true },
  );
  function getCondition(data: Recordable) {
    if (isCreateRule.value) {
      alarm.value.createRule[whoEdit.value].condition = _.cloneDeep(data);
    } else {
      alarm.value.clearRules[whoEdit.value].condition = _.cloneDeep(data);
    }
  }
  function getSchedule(data: Recordable) {
    if (isCreateRule.value) {
      alarm.value.createRule[whoEdit.value].schedule = _.cloneDeep(data);
    } else {
      alarm.value.clearRules[whoEdit.value].schedule = _.cloneDeep(data);
    }
  }
  //打开条件弹窗
  function toCondition(index: number, flag: boolean) {
    isCreateRule.value = flag;
    whoEdit.value = index;
    openAlertCondition();
  }
  //打开启用弹窗
  function toSchedule(index: number, flag: boolean) {
    isCreateRule.value = flag;
    whoEdit.value = index;
    openAlertSchedule();
  }
  function toEditCondition(index: number, data: Recordable, flag: boolean) {
    isCreateRule.value = flag;
    whoEdit.value = index;
    openAlertCondition(true, data.condition);
  }

  function toEditSchedule(index: number, data: Recordable, flag: boolean) {
    isCreateRule.value = flag;
    whoEdit.value = index;
    openAlertSchedule(true, data.schedule);
  }
</script>

<style lang="less" scoped>
  .ant-collapse :deep(.ant-collapse-item > .ant-collapse-header) {
    align-items: center;
  }
  .item {
    display: flex;
    flex-direction: column;
    margin-bottom: 18px;
  }
  .alarm-rules {
    .checkBox {
      display: flex;
      flex-direction: column;
      .ant-checkbox-wrapper {
        margin-left: 0px;
      }
    }
    .add-alarm-box {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: inherit;
      margin-bottom: 24px;
      box-sizing: border-box;
      .add-alarm-card {
        display: flex;
        flex-direction: row;
        border: 2px solid #dbdbdb;
        width: 96%;
        flex: 1;
        .item {
          display: flex;
          flex-direction: row;
          align-items: center;
        }
        .left {
          padding: 20px;
          width: 30%;
        }
        .right {
          display: flex;
          flex-direction: column;
          padding: 20px;
          flex: 1;
          overflow: hidden;
          .condition {
            margin-bottom: 18px;
            display: flex;
            flex-direction: row;
            align-items: center;
            .ellipsis {
              display: flex;
              align-items: center;
              white-space: nowrap; /* 禁止文本换行 */
              text-overflow: ellipsis; /* 当内容溢出时显示省略号 */
              overflow: hidden; /* 隐藏超出部分的内容 */
            }
          }
        }
      }
    }
  }
  .ant-btn {
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
